Ext.namespace("Dudley");
Ext.namespace("Dudley.lims");

Dudley.lims.YSEQRadtag = function() {

    var myRadtagData = [];
    var radtagForm = {};
    var radPanel = {};
    var radtagHash = null;
    var radtagCount = null;
    var radtagMaxNum = null;
    var radtagStore = null;
    var radtagLoaded = false;
    var initSearchUrl = getRadtagSearchUrl("FREE_TEXT=randomFakeData", "", "");

    function initRadtagStore(failedCb, callback) {
        loadRadtagSearchResult(0, null, callback);
    }

    function loadRadtagSearchResult(index, searchResultJSON, callback) {
        myRadtagData = [];
        if (searchResultJSON != null) {
            if (searchResultJSON.results != null) {
                var jsonSearchArray = searchResultJSON.results;
                for (var i = 0; i < jsonSearchArray.length; i++) {
                    myRadtagData[index + i] = translateRadtagResultToJson(jsonSearchArray[i]);
                }
            }
        }
        radtagStore = new Ext.ux.data.PagingArrayStore({
            fields: getRadtagPagingColumns(),
            data: myRadtagData,
            sortInfo: {field:'indexNum', direction:'ASC'}
        });
        radtagStore.load({params:{start:0, limit:20}}, callback());
    }

    function goSearch(index, radtagSearchInput, radtagSearchOption) {
        radtagSearchInput = radtagSearchInput + "";
        //replace all blanks with %20
        radtagSearchInput = radtagSearchInput.replace(/ /g, "%20");
        var freeSearchOp = "FREE_TEXT=" + radtagSearchInput;
        var matchingAllTerms = "MATCHING_ALL_TERMS=true";
        var matchingSearchHash = "";
        if (radtagSearchOption == null || radtagSearchOption == 'All' || radtagSearchOption == '') {
            matchingAllTerms = "";
            if (radtagSearchInput == '') {
                radtagSearchInput = '*';
            }
        } else {
            freeSearchOp = "";
            matchingSearchHash = "&" + radtagSearchOption + "=" + radtagSearchInput;
        }
        var searchUrl = getRadtagSearchUrl(freeSearchOp, matchingAllTerms, matchingSearchHash);
        var searchWin = new Ext.Window({
            title: 'Loading Radtag',
            width: 400,
            minWidth: 350,
            height: 150,
            modal: true,
            closeAction: 'hide',
            bodyStyle: 'padding:10px;',
            html: "Loading Radtags...",
            bbar: new Ext.ux.StatusBar({
                id: 'search-radtag-statusbar',
                defaultText: 'Ready'
            })
        });
        searchWin.on("show", function () {
            var sb = Ext.getCmp("search-radtag-statusbar");
            sb.showBusy();
        });
        searchWin.show();
        Ext.Ajax.request({
            url: searchUrl,
            method: "GET",
            success: function(response) {
                var searchResultObj = Ext.util.JSON.decode(response.responseText);
                eventManager.fireStatusMessageEvent({ text: "Radtag Search Results Count:" + searchResultObj.numberOfResults, level: "info" });
                myRadtagData = [];
                loadRadtagSearchResult(index, searchResultObj, function() {
                    Ext.getDom("sample-search-result-list").innerHTML = "";
                    Ext.getDom("yo-form").innerHTML = "";
                    searchWin.close();
                    renderRadtagSearchResult();
                });
            },
            failure: function() {
                eventManager.fireStatusMessageEvent({ text: "Search Results failed for url:" + searchUrl, level: "error" });
            }
        });
    }

    function loadRadtagPanel() {
        var radtagsOptionsData = getRadtagSearchOptionsArray();
        var radtagsOptionsStore = new Ext.data.SimpleStore({
            fields: ['key', 'value'],
            data : radtagsOptionsData
        });
        var radtagCombo = new Ext.form.ComboBox({
            store: radtagsOptionsStore,
            name: 'radtagCombo',
            id: 'radtagComboId',
            fieldLabel: 'On Fields',
            displayField:'value',
            valueField:'key',
            typeAhead: true,
            mode: 'local',
            emptyText:'All',
            triggerAction: 'all',
            forceSelection:true,
            selectOnFocus:true
        });
        var radtagSearchForm = new Ext.form.FormPanel({
            id: 'radtagSearchForm',
            method: 'POST',
            autoHeight: true,
            width: 800,
            buttonAlign: 'center',
            title: '',
            keys: [
                {
                    key: [Ext.EventObject.ENTER],
                    fn: function() {
                        Ext.ComponentMgr.get('radtagSearchButtonId').fireEvent('click');
                    }
                }
            ],

            items: [
                {
                    layout:'column',
                    items:[
                        {
                            columnWidth:.75,
                            border: false,
                            layout: 'form',
                            items: [
                                {
                                    xtype:'textfield',
                                    fieldLabel: 'Search',
                                    id: 'radtagSearchInputId',
                                    name: 'radtagSearchInput',
                                    anchor:'95%'
                                }
                            ]
                        },
                        {
                            layout: 'form',
                            border: false,
                            items: [
                                {
                                    xtype: 'button',
                                    fieldAlign: 'center',
                                    text: '&nbsp;&nbsp;Search&nbsp;&nbsp;',
                                    id: 'radtagSearchButtonId',
                                    listeners:{click:
                                            function() {
                                                var searchInput = Ext.getCmp("radtagSearchInputId").getValue();
                                                var searchOption = radtagCombo.getValue();
                                                goSearch(0, searchInput, searchOption);
                                            }}
                                }
                            ]
                        },
                        {
                            columnWidth:1,
                            layout:'form',
                            items: [radtagCombo]
                        }
                    ]
                }
            ]
        });
        var tbarButtons = [
            {
                id: 'showRadtagSearchResultsId',
                name: 'showRadtagSearchResults',
                disabled: true,
                text: '<--Search Results',
                icon: "images/back-green.png",
                cls:'x-btn-text-icon',
                listeners: {click:
                        function() {
                            Ext.getDom("yo-form").innerHTML = "";
                            renderRadtagSearchResult();
                        }
                }
            },
            {
                id: 'searchAllRadtagId',
                name: 'searchAllRadtag',
                disabled: false,
                text: 'View All Records',
                icon: "images/search-blue.png",
                cls:'x-btn-text-icon',
                listeners: {click:
                        function() {
                            Ext.getDom("yo-form").innerHTML = "";
                            goSearch(0, '*', 'All');
                        }
                }
            },
            {
                id: 'createNewRadtagId',
                name: 'createNewRadtag',
                text: 'Create New Radtag',
                icon: "images/add-green.png",
                cls:'x-btn-text-icon',
                listeners: {click:
                        function() {
                            Dudley.lims.YSEQRadtag.loadNewRadtag();
                        }
                }
            }
        ];
        radPanel = new Ext.Panel({
            id: "radPanelId",
            autoHeight: true,
            border: true,
            renderTo: "yad-panel",
            title: "Multiplex",
            header: false,
            tbar: tbarButtons,
            items: radtagSearchForm
        });
        /*radPanel.on("activate", function () {
         Ext.getDom("yo-panel").innerHTML = "";
         Ext.getDom("yo-form").innerHTML = "";
         Ext.getDom("sample-search-result-list").innerHTML = "";
         if (radtagLoaded == false) {
         radtagLoaded = true;
         goSearch(0, 'CHEM*', 'radtagKey');
         }
         renderRadtagSearchResult();
         });*/
    }

    function postRadtagStrain(createNew) {
        var radtagJson = new Object();
        var radtagKey = Ext.getCmp("radtagKeyId").getValue();
        radtagJson["radtagKey"] = radtagKey;
        radtagJson["radtagName"] = Ext.getCmp("radtagNameId").getValue();
        radtagJson["alias"] = Ext.getCmp("radtagAliasId").getValue();
        radtagJson["location"] = Ext.getCmp("radtagLocationId").getValue();
        radtagJson["keyword"] = Ext.getCmp("radtagKeywordId").getValue();
        radtagJson["reorderKey"] = Ext.getCmp("radtagReorderId").getValue();
        radtagJson["comments"] = Ext.getCmp("radtagCommentsId").getValue();

        var strainOp = "create";
        var radtagCallback = function() {
            var radtagAnnoJson = new Object();
            radtagAnnoJson['radtagMaxNum'] = radtagMaxNum;
            radtagAnnoJson['radtagCount'] = radtagCount;
            postDudleyAnnotations('/addama-rest/dudley-sample/path/datasource/Radtag/annotations', radtagAnnoJson, function() {
                eventManager.fireStatusMessageEvent({ text: "New Radtag Strain Added Successfully", level: "info" });
                Ext.Msg.alert('Info', "New Radtag " + radtagKey + ' Added Successfully');
                Ext.getDom("yo-form").innerHTML = "";
                goSearch(0, radtagKey, "radtagKey");
            });
        };
        if (!createNew) {
            strainOp = "annotations";
            radtagCallback = function() {
                Ext.Msg.alert('Info', radtagKey + ' Updated Successfully');
                var searchResultsButton = Ext.getCmp("showRadtagSearchResultsId");
                searchResultsButton.disable();
            };
        }
        var radtagUrl = "/addama-rest/dudley-sample/path/datasource/Radtag/" + radtagKey + "/" + strainOp;
        postDudleyAnnotations(radtagUrl, radtagJson, radtagCallback);
    }

    function loadCreateRadtagStrain(radtagHash, callback) {
        var createNew = true;
        var buttons = [
            {
                id: 'createButton',
                name: 'createButton',
                text: 'Create',
                listeners: {click:
                        function() {
                            if (validateCreateUpdateRadtag()) {
                                postRadtagStrain(createNew);
                            }
                        }
                }
            }
        ];
        if (radtagHash != null) {
            if (radtagHash.genotype != undefined && radtagHash.genotype == 'Record Deleted') {
                buttons = [];
            } else {
                buttons = [
                    {
                        id: 'updateRadtagButtonId',
                        name: 'updateRadtagButton',
                        text: 'Update',
                        listeners: {click:
                                function() {
                                    if (validateCreateUpdateRadtag()) {
                                        postRadtagStrain(!createNew);
                                    }
                                }
                        }
                    },
                    {
                        id: 'deleteRadtagButtonId',
                        name: 'deleteRadtagButton',
                        text: 'Delete',
                        //disabled: true,
                        listeners: {click:
                                function() {
                                    var deleteUrl = "/addama-rest/dudley-sample/path/datasource/Radtag/" + radtagHash.name + "/annotations/?JSON={deleteradtag:true}";
                                    Ext.Msg.confirm('Message', "Please confirm that you want to delete " + radtagHash.name + "", function(btn) {
                                        if (btn == 'yes') {
                                            Ext.Ajax.request({
                                                url: deleteUrl,
                                                method: "POST",
                                                success: function() {
                                                    Ext.Msg.alert(radtagHash.name + " deleted, Radtag Strains Reloading...");
                                                    goSearch(0, '*', 'All');
                                                },
                                                failure: function() {
                                                    eventManager.fireStatusMessageEvent({ text: "Delete Failed for " + radtagHash.name, level: "error" });
                                                }
                                            });
                                        }
                                    });
                                }
                        }
                    }
                ];
            }
        } else {
            radtagHash = new Object();
            var radtagMaxInt = parseInt(radtagMaxNum);
            radtagMaxInt = radtagMaxInt + 1;
            var radtagCountInt = parseInt(radtagCount);
            radtagCountInt = radtagCountInt + 1;
            radtagCount = radtagCountInt + "";
            radtagHash.name = 'CHEM' + radtagMaxInt;
            radtagMaxNum = radtagMaxInt + "";
            if (radtagHash.comments == null) {
                radtagHash.comments = "";
            }

        }
        radtagForm = new Ext.form.FormPanel({
            id: 'radtagForm',
            method: 'POST',
            autoHeight: true,
            autoScroll: true,
            border: true,
            buttonAlign: 'left',
            buttons: buttons,
            items: [
                new Ext.form.FieldSet({
                    autoHeight: true,
                    border: false,
                    items: [
                        new Ext.form.TextField({
                            id: "radtagKeyId",
                            fieldLabel: "Key",
                            name: "radtagKey",
                            value: radtagHash.name,
                            width: 500,
                            readOnly: true,
                            allowBlank: false
                        }),
                        new Ext.form.TextField({
                            id: "radtagNameId",
                            fieldLabel: "Name",
                            name: "radtagName",
                            value: radtagHash.radtagName,
                            width: 500,
                            allowBlank: false
                        }),
                        new Ext.form.TextField({
                            id: "radtagAliasId",
                            fieldLabel: "Alias",
                            value: radtagHash.alias,
                            width: 500,
                            allowBlank: false,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Shorter version/nickname of radtag'
                                    });
                                }
                            }
                        }),
                        new Ext.form.TextField({
                            id: "radtagKeywordId",
                            fieldLabel: "Keyword",
                            value: radtagHash.keyword,
                            width: 500,
                            allowBlank: false,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Enter category of the radtag, ie amino acid, antibody, detergent, stain, ... etc'
                                    });
                                }
                            }
                        }),
                        new Ext.form.TextField({
                            id: "radtagLocationId",
                            fieldLabel: "Location",
                            name: "radtagLocation",
                            value: radtagHash.location,
                            width: 500,
                            allowBlank: false
                        }),
                        new Ext.form.TextField({
                            id: "radtagReorderId",
                            fieldLabel: "Reorder",
                            name: "radtagReorder",
                            value: radtagHash.reorderKey,
                            width: 500,
                            allowBlank: true,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Company, catalog number, reorder number, qty'
                                    });
                                }
                            }
                        }),
                        {
                            xtype:'htmleditor',
                            id:'radtagCommentsId',
                            value: radtagHash.comments,
                            fieldLabel:'Comments ' + '<br><i><font size=-2>Relevant information, such as safety info, about the radtag not covered in other fields</font></i>',
                            height:100,
                            labelSeparator: '',
                            anchor:'98%',
                            listeners: {
                                activate: function(e) {
                                    if (radtagHash.comments == undefined || radtagHash.comments == "") {
                                        e.execCmd('delete');
                                    }
                                }
                            }
                        }
                    ]
                })
            ]
        });
        callback();

    }


    // render the grid to the specified div in the page
    function renderRadtagSearchResult() {
        var searchResultsButton = Ext.getCmp("showRadtagSearchResultsId");
        if (searchResultsButton != null || searchResultsButton != undefined) {
            searchResultsButton.disable();
        }

        var searchResultsGrid = new Ext.grid.GridPanel({
            id: "radtagSearchResultsId",
            store: radtagStore,
            columns: getRadtagSearchColumnHeaders(),
            stripeRows: true,
            autoHeight: true,
            width: 800,
            title: 'Radtag',
            renderTo: "sample-search-result-list",
            bbar: new Ext.PagingToolbar({
                pageSize: 20,
                store: radtagStore,
                displayInfo: true,
                displayMsg: 'Displaying strains {0} - {1} of {2}',
                emptyMsg: "No strains to display"
            })
        });
        searchResultsGrid.on("celldblclick", function (g, ri, ci, e) {
            var searchResultsButton = Ext.getCmp("showRadtagSearchResultsId");
            searchResultsButton.enable();
            radtagHash = new Object();
            populateRadtagJson(radtagHash, g);
            var resourceUri = "/addama-rest/dudley-sample/path/datasource/Radtag/" + radtagHash.name;
            Ext.Ajax.request({
                url: resourceUri + "/mayUpdate",
                method: "GET",
                params: {
                    "user_uri": LoggedInUser.userUri
                },
                success: function() {
                    loadCreateRadtagStrain(radtagHash, function() {
                        radtagFormRender();
                    });
                },
                failure: function() {
                    eventManager.fireStatusMessageEvent({ text: "Read only access allowed", level: "info" });
                    loadCreateRadtagStrain(radtagHash, function() {
                        var updateRadtagButton = Ext.getCmp("updateRadtagButtonId");
                        if (updateRadtagButton != undefined) {
                            updateRadtagButton.hidden = true;
                        }
                        var deleteRadtagButton = Ext.getCmp("deleteRadtagButtonId");
                        if (deleteRadtagButton != undefined) {
                            deleteRadtagButton.hidden = true;
                        }
                        radtagFormRender();
                    });
                }
            });

        });
    }

    function radtagFormRender() {
        Dudley.lims.samplemgr.getHousingPanel().activate(radPanel);
        Ext.getDom("sample-search-result-list").innerHTML = "";
        Ext.getDom("yo-form").innerHTML = "";
        radtagForm.render("yo-form");
    }

    // public
    return {
        initRadtag: function(failedCB) {
            initRadtagStore(failedCB, function() {
                eventManager.fireStatusMessageEvent({ text: "Finishing init Radtag Store", level: "info" });
            });
        },

        getRadtagPanel: function() {
            loadRadtagPanel();
            return radPanel;
        },

        getRadtagInst: function() {
            return radPanel;
        },

        getCGSStore: function() {
            return radtagStore;
        },
         /*
        loadMockupImage: function(callback) {
            loadKaryomapStatic("pv-canvas", function(mockform) {
                Dudley.lims.sequencingmgr.clearPane();
                Dudley.lims.sequencingmgr.getOmicPanel().add(mockform).show();
                callback();
            });
        },
        */
        loadNewRadtag: function() {
            Ext.getDom("wo-form").innerHTML = "";
            if (LoggedInUser.userUri == "/addama-users/users/public@systemsbiology.org") {
                Ext.Msg.alert("warning", "You not have permission to create new radtags");
            } else {
                Ext.Ajax.request({
                    url: "/addama-rest/dudley-sample/path/datasource/CGS/annotations",
                    method: "GET",
                    success: function(response) {
                        var yoAnnoObj = Ext.util.JSON.decode(response.responseText);
                        radtagCount = yoAnnoObj.radtagCount;
                        radtagMaxNum = yoAnnoObj.radtagMaxNum;
                        radtagHash = null;
                        var searchResultsButton = Ext.getCmp("showRadtagSearchResultsId");
                        searchResultsButton.enable();
                        loadCreateRadtagStrain(radtagHash, function() {
                            Dudley.lims.sequencingmgr.clearPane();
                            radtagForm.render("wo-form");
                        });
                    },
                    failure: function() {
                        eventManager.fireStatusMessageEvent({ text: "Failed Getting Annotations for Radtag Datasource", level: "error" });
                    }
                });
            }
        },
        loadSearchResult: function() {
            Ext.getDom("sample-search-result-list").innerHTML = "";
            renderRadtagSearchResult();
        }

    };
}();
